import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { ScrollView, View } from "@tarojs/components";

import Sticky from "@/components/app/Sticky";
import ByButton from "@/components/ui/ByButton";
import CartProductItem from "./components/CartProductItem";
import TreeMenu from "@/packageProject/components/TreeMenu";

import useFetch from "@/hooks/useFetch";
import ApiMaterial from "@/api/material";

import { MaterialChooseTemp } from "@/types/material";
import { useUpdateEffect } from "ahooks";

export default () => {
  const { params } = useRouter();
  const chooseType = Number(params.chooseType);
  const intentCustomerId = Number(params.intentCustomerId);

  // 根据意向客户ID获取材料模板
  const { data, refresh } = useFetch<MaterialChooseTemp>(
    ApiMaterial.getMaterialInfoByintendId,
    {
      showLoading: true,
      defaultParams: [{ intentCustomerId, chooseType }],
      onSuccess(res) {
        const newMap = new Map();
        // 把模板内的材料转成map形式
        res.Areas.forEach((area) => {
          area.DetailDTOList.forEach((item) => {
            item.MaterialCode && newMap.set(item.MaterialCode, item);
          });
        });
      },
    }
  );

  // 提交 确认 选材
  const { loading, run: submit } = useFetch(ApiMaterial.submit, "POST", {
    manual: true,
    onSuccess() {
      Taro.showToast({ title: "操作成功！" });
      setTimeout(() => {
        Taro.reLaunch({
          url: `/packageProject/pages/success/index?intentCustomerId=${intentCustomerId}&title=选材成功&subtitle=等待客户确认`,
        });
      }, 1500);
    },
  });

  // 确认选材
  const handleSubmit = async () => {
    const { confirm } = await Taro.showModal({ title: "确认已选好材料！" });
    if (confirm)
      submit({
        chooseMasterId: data!.chooseMasterId,
      });
  };

  // 材料列表
  const areaList = data?.Areas || [];
  // 激活的类别
  const [activeIndex, setActiveIndex] = useState<number>(0);
  const [materialList, setMaterialList] = useState<any[]>([]);

  useUpdateEffect(() => {
    const list = areaList[activeIndex]?.DetailDTOList || [];
    setMaterialList(list);
  }, [activeIndex, areaList]);

  // 更新已选数据
  const { run: updateChooseMaterial } = useFetch(
    ApiMaterial.materialChooseModify,
    "POST",
    { manual: true, showLoading: true }
  );

  // 删除项
  const removeItem = async (index) => {
    const list = areaList[activeIndex]?.DetailDTOList;
    const target = list[index];
    const flag = (target.IsReduce = !target.IsReduce);

    const { confirm } = await Taro.showModal({
      title: `确定${flag ? "" : "取消"}减配该项选材？`,
    });

    if (confirm) {
      await updateChooseMaterial({
        num: target.Num,
        remark: target.Remark,
        chooseId: target.ChooseId,
        materialId: target.MaterialId,
        materialName: target.MaterialName,
        materialPrice: target.MaterialPrice,
        usePriceName: target.UsePriceName,
        color: target.Color,
        Standard: target.Standard,
        // -1未选材， 0已选
        status: target.State,
        isReduce: flag,
      });

      setMaterialList([...list]);
    }
  };

  return (
    <View className="h-screen flex flex-col">
      <View className="flex-auto relative overflow-hidden">
        <View className="absolute top-0 bottom-0 left-0 w-[200px] bg-[#f1f3f8] z-10 h-full">
          <TreeMenu
            active={activeIndex}
            list={areaList}
            labelKey="Area"
            onClick={setActiveIndex}
          />
        </View>

        <ScrollView scroll-y className="pl-[200px] h-full">
          <View className="px-2">
            {materialList.map((item, index) => (
              <CartProductItem
                disabled
                shouActions
                source={item}
                key={item.ChooseId}
                onRemove={() => removeItem(index)}
                onReset={refresh}
              />
            ))}
          </View>
        </ScrollView>
      </View>

      <Sticky className="z-[100] flex px-4 py-3 bg-page">
        <ByButton
          variant="outline"
          className="flex-1"
          size="large"
          disabled={loading}
          onClick={() => Taro.navigateBack({ delta: 1 })}
        >
          继续添加
        </ByButton>
        <ByButton
          className="ml-3 flex-2"
          size="large"
          loading={loading}
          onClick={handleSubmit}
        >
          提交选材单
        </ByButton>
      </Sticky>
    </View>
  );
};
